package com.example.socketchat.server;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import jakarta.annotation.PostConstruct;
import jakarta.annotation.PreDestroy;

@Slf4j
@Component
public class NettyServer {

    @Value("${socket.server.port}")
    private int port;

    @Autowired
    private ServerBootstrap serverBootstrap;

    @Autowired
    private ChatServerInitializer chatServerInitializer;

    private Channel serverChannel;

    @PostConstruct
    public void start() throws Exception {
        try {
            // 设置childHandler
            serverBootstrap.childHandler(chatServerInitializer);
            
            // 绑定端口并启动服务器
            serverChannel = serverBootstrap.bind(port).sync().channel();
            
            log.info("Netty服务器已启动，监听端口: {}", port);
        } catch (Exception e) {
            log.error("Netty服务器启动失败", e);
            throw e;
        }
    }

    @PreDestroy
    public void stop() {
        if (serverChannel != null) {
            serverChannel.close();
            log.info("Netty服务器已关闭");
        }
    }
} 